package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        // 获取微信接口返回的openid
        String openid = getWxOpenId(userLoginDTO.getCode());
        // 检查openid是否为空
        if (openid == null || openid.equals("")){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 检查该用户是否为新用户-第一次登录
        User user = userMapper.selectByOpenid(openid);
        // 如果是，则自动为该用户完成注册
        if (user == null){
            user  = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 返回user对象
        return user;
    }

    /**
     * 获取微信openid的接口
     */
    public String getWxOpenId(String code){
        // 获取openid
        Map<String, String> paramMap;
        paramMap = Map.of(
                "appid", weChatProperties.getAppid(),
                "secret", weChatProperties.getSecret(),
                "js_code",code,
                "grant_type", "authorization_code"
        );
        String s = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        JSONObject  jsonObject = JSONObject.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
